//
//  CZOAuthViewController.swift
//  Weibo28
//
//  Created by Apple on 16/5/11.
//  Copyright © 2016年 itcast. All rights reserved.
//

import UIKit
import SVProgressHUD
import AFNetworking

//  新浪微博的appkey
let WeiboAppKey = "3469971745"
//  授权回调页
let WeiboRedirect_Uri = "http://www.itcast.cn"
//  AppSecret 获取accesstoken
let WeiboAppSecret = "2f97a04674990b2ebd957bbe86efe626"

class CZOAuthViewController: UIViewController {
    //  MARK:   --懒加载
    //  创建webview
    private lazy var webView: UIWebView = UIWebView()
    
    //  自定义view
    override func loadView() {
        //  设置代理
        webView.delegate = self
        
        view = webView
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        setupNavUI()
        //  请求登陆地址
        let url = "https://api.weibo.com/oauth2/authorize?client_id=\(WeiboAppKey)&redirect_uri=\(WeiboRedirect_Uri)"
        let request = NSURLRequest(URL: NSURL(string: url)!)
        
        print(url)
        //  加载登陆页面
        webView.loadRequest(request)
       
    }
    
    private func setupNavUI() {
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "取消", fontSize: 15, target: self, action: "cancelAction")
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动填充", fontSize: 15, target: self, action: "autoFillAction")
        navigationItem.title = "微博登陆"
    }
    
    //  MARK:   - 点击事件
    @objc private func cancelAction() {
        print("cancelAction")
        dismissViewControllerAnimated(true, completion: nil)
    }
    
    @objc private func autoFillAction() {
          print("autoFillAction")
        webView.stringByEvaluatingJavaScriptFromString("document.getElementById('userId').value = 'hao123guohaibin@163.com'; document.getElementById('passwd').value = 'guohaibin012'")
    }
    
    
    
    // 通过code  获取accesstoken
    //  代码已经抽取到viewModel
//    private  func requestAccessToken(code: String) {
//        
//        
//        CZNetWorkTools.sharedTools.requestAccessToken(code) { (response, error) -> () in
//            if error != nil {
//                print("网络请求异常")
//                return
//            }
//            
//            //  代码执行到此 网络请求成功
//            
//            guard let dic = response as? [String: AnyObject] else {
//                print("数据不是一个正确的json格式")
//                return
//            }
//
//            //  代码执行到此一定是字典
//            let userAccount = CZUserAcount(dic: dic)
//            print(userAccount)
//            self.requestUserInfo(userAccount)
//            
//            
//        }
//        
//        
//        
////        //  创建url
////        let url = "https://api.weibo.com/oauth2/access_token"
////        //  设置参数
////        let params = [
////            "client_id": WeiboAppKey,
////            "client_secret": WeiboAppSecret,
////            "grant_type": "authorization_code",
////            "code": code,
////            "redirect_uri": WeiboRedirect_Uri
////        ]
////        
////        let sessionManager = AFHTTPSessionManager()
////        sessionManager.responseSerializer.acceptableContentTypes?.insert("text/plain")
////        sessionManager.POST(url, parameters: params, progress: nil, success: { (_, response) -> Void in
////            
////            guard let dic = response as? [String: AnyObject] else {
////                print("数据不是一个正确的json格式")
////                return
////            }
////            
////            //  代码执行到此一定是字典
////            let userAccount = CZUserAcount(dic: dic)
////            print(userAccount)
////            self.requestUserInfo(userAccount)
////            
////            }) { (_, error) -> Void in
////                print(error)
////        }
//    
//    }
    
    //  获取用户信息
//    private func requestUserInfo(userAccount: CZUserAcount) {
//        
//        CZNetWorkTools.sharedTools.requestUserInfo(userAccount) { (response, error) -> () in
//            
//            if error != nil {
//                print("网络请求异常")
//                return
//            }
//            //  判断json格式
//            guard let dic = response as? [String: AnyObject] else {
//                print("不是一个正确的json数据")
//                return
//            }
//
//            //  代码执行到此是一个正确的字典格式
//            userAccount.name = dic["name"] as? String
//            userAccount.avatar_large = dic["avatar_large"] as? String
//            
//            userAccount.saveUserAccount()
//
//        }
//        
//        
//        
////        //  url
////        let url = "https://api.weibo.com/2/users/show.json"
////        //  设置参数
////        let params = [
////            "access_token": userAccount.access_token!,
////            "uid": "\(userAccount.uid)"
////        ]
////        let sessionManager = AFHTTPSessionManager()
////        sessionManager.responseSerializer.acceptableContentTypes?.insert("text/plain")
////        sessionManager.GET(url, parameters: params, progress: nil, success: { (_, response) -> Void in
////            
////            guard let dic = response as? [String: AnyObject] else {
////                print("不是一个正确的json数据")
////                return
////            }
////            
////            //  代码执行到此是一个正确的字典格式
////            userAccount.name = dic["name"] as? String
////            userAccount.avatar_large = dic["avatar_large"] as? String
////            
////            print(userAccount)
////            
////            }) { (_, error) -> Void in
////                print(error)
////        }
//
//    
//    }
  

}

//  实现UIWebView代理方法

extension CZOAuthViewController: UIWebViewDelegate {
    
    //  将要加载函数请求方法
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        
        print(request.URL?.absoluteString)
        
        guard let url = request.URL else {
            
            //  假如地址为nil,就不执行加载
            return false
        }
        //  取反就是不是我们想要关心的url
        if !url.absoluteString.hasPrefix(WeiboRedirect_Uri) {
            return true
        }
        
        //  代码执行到此,就是我们需要关心的这个url
        //  query就是我们请求指定里面的参数
       //   以我们code大头我们才去截取
        if let query = url.query where query.hasPrefix("code=") {
            
            let code = query.substringFromIndex("code=".endIndex)
            print(code)
            //requestAccessToken(code)
            CZUserAccountViewModel.sharedUserAccount.requestAccessToken(code, complete: { (isSuccess) -> () in
                if isSuccess {
                    print("登陆成功")
                    //  dismis当前控制器
                    //  需要当前控制dismis完成以后才送通知切换根视图控制器
                    self.dismissViewControllerAnimated(false, completion: { () -> Void in
                        //  进入欢迎页面
                        NSNotificationCenter.defaultCenter().postNotificationName(SwitchRootVCNotification, object: self)
                    })
                   
                } else {
                    SVProgressHUD.showErrorWithStatus("登陆失败")
                }
            })
        } else {
            //  取消回调页
            dismissViewControllerAnimated(true, completion: nil)
        }

        
        
        
        return false
    }
    //  开始加载请求
    func webViewDidStartLoad(webView: UIWebView) {
        SVProgressHUD.show()
    }
    //  加载请求完成
    func webViewDidFinishLoad(webView: UIWebView) {
        SVProgressHUD.dismiss()
    }
    
    //  加载失败
    func webView(webView: UIWebView, didFailLoadWithError error: NSError?) {
        SVProgressHUD.dismiss()
    }

}











